//
//  JTTopicVoiceView.m
//  百思不得姐
//
//  Created by Robin Zhang on 2017/1/13.
//  Copyright © 2017年 BeiJingWangDianJieTong. All rights reserved.
//

#import "JTTopicVoiceView.h"
#import "JTTopic.h"
#import <UIImageView+WebCache.h>
#import "JTSeeBigPictureViewController.h"

/** 音频播放 */
#import <AVFoundation/AVFoundation.h>

#import <AFNetworking.h>
#import "JTProgressHUD.h"
#import <UIImage+GIF.h>

@interface JTTopicVoiceView () <AVAudioPlayerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *playCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *voiceTimeLabel;
@property (weak, nonatomic) IBOutlet UIButton *playButton;

@end

@implementation JTTopicVoiceView

#pragma mark - 初始化
- (void)awakeFromNib {
    [super awakeFromNib];

    [self setAutoresizingMask:UIViewAutoresizingNone];
    
    // 给imageView添加点击手势
    [self.imageView setUserInteractionEnabled:YES];
    [self.imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(seeBig:)]];
    
    /** 清空背景色 */
//    [self.playCountLabel setBackgroundColor:[UIColor clearColor]];
//    [self.voiceTimeLabel setBackgroundColor:[UIColor clearColor]];
    
    [self.playButton setImage:[UIImage sd_animatedGIFNamed:@"timg"] forState:UIControlStateDisabled];
    [self.playButton.layer setCornerRadius:self.playButton.jt_width * 0.5];
    [self.playButton.layer setMasksToBounds:YES];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setTopic:(JTTopic *)topic {
    
    _topic = topic;
    
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:topic.largeImage]];
    [self.playCountLabel setText:[NSString stringWithFormat:@"%ld次播放", topic.playcount]];
    NSInteger minute = topic.voicetime / 60;
    NSInteger second = topic.voicetime % 60;
    
    /**
     %04ld - 占据4位，多余的用0来填补
     */
    [self.voiceTimeLabel setText:[NSString stringWithFormat:@"%02ld:%02ld", minute, second]];
    
    // 设置播放按钮的播放状态
    [self.playButton setSelected:topic.audioPlayer.isPlaying];
    [self.playButton setEnabled:topic.isEnabled];
    
    // 监听通知
    // 1.暂停播放
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(voiceDidPause:) name:JTVoiceDidPauseNotification object:topic];
    // 2.音频数据下载完毕
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(voiceDidDownload:) name:JTVoiceDidDownloadNotification object:topic];
}

#pragma mark - 监听
- (void)seeBig:(UITapGestureRecognizer *)recognizer {
    
    JTSeeBigPictureViewController *viewController = [[JTSeeBigPictureViewController alloc] init];
    [viewController setTopic:self.topic];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:viewController animated:YES completion:nil];
    
//    AVPlayer
}

- (IBAction)voiceButtonDidClick:(UIButton *)sender {
    
    // 1.根据button状态开始播放或者停止播放
    if (!sender.selected) { // 开始播放
        
        // 发送通知，表示另一个音频开始播放了
        [[NSNotificationCenter defaultCenter] postNotificationName:JTAnotherVoiceDidPlayNotification object:nil];
        
        // 2.1 如果之前播放过并被暂停了，那就继续播放
        if (self.topic.audioPlayer) {
            
            [self.topic.audioPlayer play];
            [sender setSelected:YES];
            return;
        }
        
        // 2.2 之前没有播放过，那就请求数据并播放
        // 2.2.1 禁止点击并且播放加载动画
        [sender setEnabled:NO];
        
        // 2.2.2 获得AVAudioPlayer
        [self.topic setUpAudioPlayerWithDelegate:self completion:nil];
    }
    else { // 暂停
        
        [self.topic.audioPlayer pause];
        [[NSNotificationCenter defaultCenter] postNotificationName:JTVoiceDidPauseNotification object:self.topic];
    }
}

#pragma mark - 监听通知
/**
 1.音频暂停
 */
- (void)voiceDidPause:(NSNotification *)notification {
    
    [self.playButton setSelected:NO];
}

/**
 2.声音被加载完毕了
 */
- (void)voiceDidDownload:(NSNotification *)notification {
    
    [self.playButton setEnabled:YES];
    [self.playButton setSelected:YES];
}

#pragma mark - <AVAudioPlayerDelegate>
/** 1.播放结束 */
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    
    JTLog(@"播放音频结束了");
    [self.playButton setSelected:NO];
}

/** 2.解析音频出错 */
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
    
    JTLog(@"解析音频出错");
    [self.playButton setEnabled:YES];
}

/** 3.播放(开始)被中断
    原因：例如接电话等导致播放被中断
 */
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
    
    JTLog(@"播放音频中断");
}

/** 4.播放中断结束
 */
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player {
    
    [self.topic.audioPlayer play];
}

@end
